const canvas = document.getElementById('video-canvas');
const context = canvas.getContext('2d');
const room = '{{ room }}';
const username = '{{ username }}';
const inp = document.querySelector('#send-msg-inp');
const sendMsgBtn = document.querySelector('#send-msg-btn');
const messageBox = document.querySelector('#message-box');
const leaveroom = document.querySelector('#leavebutton');
const socket = io();

// 连接
socket.connect(location.protocol + '//' + document.domain + ':' + location.port);

// 加入直播间
socket.emit('join', {
  username: username,
});

// 退出直播间
leaveroom.onclick = function () {
  window.location.href = '{{ url_for('logout') }}';
  socket.emit('leave', {
    username: username,
  });
};

// 发送消息
sendMsgBtn.onclick = function () {
  let inp = document.querySelector('#send-msg-inp');
  let msg = inp.value;
  let user = document.querySelector('#username').innerHTML;
  inp.value = '';

  console.log('1111');
  if (msg) {
    socket.emit('send msg', {
      user: user,
      message: msg,
    });
    messageBox.scrollTop = messageBox.scrollHeight;
  } else {
    alert('消息不能为空');
  }
};

// 接受消息
socket.on('send msg', function (data) {
  console.log(data);
  console.log(socket.id);
  let msg = null;
  let msgbox = document.createElement('div');
  msgbox.className = 'row';
  msg = `
    <div >
      <div >
        <span ><b>${data.user}</b>:  ${data.message}
        </span>
      </div>
    </div>`;
  msgbox.innerHTML = msg;
  messageBox.appendChild(msgbox);
  messageBox.scrollTop = messageBox.scrollHeight;
});

//接收图像
socket.on('video_stream', function (data) {
  var img = new Image();
  img.onload = function () {
    context.drawImage(img, 0, 0, canvas.width, canvas.height);
  };
  img.src = 'data:image/jpeg;base64,' + data;
});